<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>

        // 两数之和
        // 输入：nums = [2,7,11,15], target = 9
        // 输出：[0,1]
        // 解释：因为 nums[0] + nums[1] == 9 ，返回 [0, 1] 。

        // 暴力解法
        function twoSum (nums, target) {
            for (let i = 0; i < nums.length; i++) {
                for (let j = 1; j < nums.length; j++) {
                    if (i !== j) {
                        if (nums[i] + nums[j] === target) {
                            return [i, j];
                        }
                    }
                }
            }
        }

        // 哈希表解法
        function twoSum (nums, target) {
            const map = {
                // 2: 0, // 数字: 索引
            };
            for (let i = 0; i < nums.length; i++) {
                const num = nums[i];
                const find = target - num;
                if (map[find] !== undefined) {
                    return [ map[find], i ];
                }
                map[num] = i;
            }
        }

        console.log( twoSum([2, 7, 11, 15], 9) ); // [0, 1]
        console.log( twoSum([3, 2, 4], 6) ); // [1, 2]


    </script>
</body>
</html>